package com.gitee.apanlh.util.sys;

import com.gitee.apanlh.exp.ClipboardException;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

/**	
 * 	剪切板工具类
 * 
 * 	@author Pan
 */
public class ClipboardUtils {
	
	/** 获取AWT工具包 */
	private static final Toolkit DEFAULT_TOOLKIT = Toolkit.getDefaultToolkit();
	
	/**
	 * 	构造函数
	 * 
	 * 	@author Pan
	 */
	private ClipboardUtils() {
		//	不允许外部实例
		super();
	}
	
	/**	
	 * 	获取剪切图片
	 * 	<br>BufferedImage cutImage = (BufferedImage) getCutImage();
	 * 	<br>落地图片示例:ImageUtils.imageWrite(cutImage, "jpg", "F:\\disc.jpg");方法
	 * 
	 * 	@author Pan
	 * 	@return Image
	 */
	public static Image getCutImage() {
		Clipboard systemClipboard = DEFAULT_TOOLKIT.getSystemClipboard();
		Transferable contents = systemClipboard.getContents(null);
		try {
			if (contents != null && checkDataFlavor(contents, DataFlavor.imageFlavor)) {
				Image transferData = (Image) contents.getTransferData(DataFlavor.imageFlavor);
				
				if (transferData != null) {
					return transferData;
				}
			}
			return null;
		} catch (Exception e) {
			throw new ClipboardException(e.getMessage(), e);
		}
	}
	
	/**	
	 * 	获取剪切板文本
	 * 	
	 * 	@author Pan
	 * 	@return String
	 */
	public static String getCutStr() {
		Transferable contents = DEFAULT_TOOLKIT.getSystemClipboard().getContents(null);
		
		if (contents != null && checkDataFlavor(contents, DataFlavor.stringFlavor)) {
			try {
				Object transferData = contents.getTransferData(DataFlavor.stringFlavor);
				
				if (transferData != null) {
					return (String) transferData;
				}
			} catch (Exception e) {
				throw new ClipboardException(e.getMessage(), e);
			}
		}
		return null;
	}
	
	/**	
	 * 	复制文本
	 * 	
	 * 	@author Pan
	 *	@param  text 文本
	 */
	public static void setCopyStr(String text) {
		DEFAULT_TOOLKIT.getSystemClipboard().setContents(new StringSelection(text), null);
	}
	
	/**	
	 * 	检测数据类型
	 * 	
	 * 	@author Pan
	 * 	@param  transferable 剪切板
	 * 	@param  dataFlavor   数据类型
	 * 	@return boolean
	 */
	private static boolean checkDataFlavor(Transferable transferable, DataFlavor dataFlavor) {
		return transferable.isDataFlavorSupported(dataFlavor);
	}
}
